<template>
  <div class="cart-page">
    <header-nav />
    
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>购物车</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="main-content">
      <el-card class="page-header-card" style="margin-top: 1.5rem;">
        <h1 class="cart-title">您的购物车 <el-tag type="info" size="small">{{ totalItems }}件商品</el-tag></h1>
      </el-card>
      
      <div v-if="loading" class="loading">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="cartItems.length === 0" class="empty-cart">
        <el-empty description="购物车是空的">
          <el-button type="primary" @click="$router.push('/')">
            去购物
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="cart-container">
        <!-- 订单摘要 - 右侧上方 -->
        <el-card class="order-summary">
          <template #header>
            <div class="card-header">
              <span>订单摘要</span>
            </div>
          </template>
          
          <div class="summary-content">
            <div class="summary-row">
              <span>商品小计:</span>
              <span>¥{{ formatPrice(subtotalAmount) }}</span>
            </div>
            
            <div class="summary-row shipping-row">
              <span>配送费:</span>
              <div class="shipping-info">
                <span>¥{{ formatPrice(shipping) }}</span>
                <el-button 
                  type="primary" 
                  link
                  @click="showShippingOptions = !showShippingOptions"
                >
                  {{ showShippingOptions ? '关闭' : '计算配送费' }}
                </el-button>
              </div>
            </div>
            
            <div v-if="showShippingOptions" class="shipping-options">
              <el-form :model="shippingAddress">
                <el-form-item label="国家/地区">
                  <el-select v-model="shippingAddress.country" placeholder="选择国家">
                    <el-option label="中国" value="CN" />
                    <el-option label="美国" value="US" />
                    <el-option label="英国" value="UK" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="省/州">
                  <el-select v-model="shippingAddress.province" placeholder="选择省份">
                    <el-option 
                      v-for="province in provinces" 
                      :key="province.value" 
                      :label="province.label" 
                      :value="province.value" 
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="城市">
                  <el-select 
                    v-model="shippingAddress.city" 
                    placeholder="选择城市"
                    :disabled="!shippingAddress.province"
                  >
                    <el-option 
                      v-for="city in cities" 
                      :key="city.value" 
                      :label="city.label" 
                      :value="city.value" 
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="邮编">
                  <el-input v-model="shippingAddress.postcode" placeholder="请输入邮编" />
                </el-form-item>
                
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="calculateShipping"
                    :loading="processingAction"
                  >
                    计算
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="summary-row address-row">
              <span style="width:30%">收货地址:</span>
              <div class="address-selector" >
                <el-select 
                  v-model="selectedAddressId" 
                  placeholder="选择收货地址"
                  @change="handleAddressChange"
                  style="width: 100%;margin-left: 1rem;"
                >
                  <el-option
                    v-for="address in addresses"
                    :key="address.id"
                    :label="formatAddressLabel(address)"
                    :value="address.id"
                  >
                    <div class="address-option">
                      <div class="address-option-name">
                        <span class="name">{{ address.name }}</span>
                        <span class="phone">{{ address.phone }}</span>
                      </div>
                      <div class="address-option-detail">{{ formatAddress(address) }}</div>
                    </div>
                  </el-option>
                </el-select>
                
                <div v-if="selectedAddress" class="selected-address-detail">
                  <div class="address-header">
                    <span class="name">{{ selectedAddress.name }}</span>
                    <span class="phone">{{ selectedAddress.phone }}</span>
                  </div>
                  <div class="address-content">
                    <i class="el-icon-location"></i>
                    <span>{{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.address }}</span>
                  </div>
                  <div v-if="selectedAddress.postcode" class="address-postcode">
                    邮编: {{ selectedAddress.postcode }}
                  </div>
                </div>
                
                <el-button 
                  type="primary" 
                  link
                  @click="showAddressDialog" style="margin-left: 13rem;"
                >
                  {{ addresses.length > 0 ? '管理地址' : '添加地址' }}
                </el-button>
              </div>
            </div>
            
            <div class="summary-row promo-row">
              <span>优惠码:</span>
              <div class="promo-input">
                <el-input v-model="promoCode" placeholder="输入优惠码" />
                <el-button 
                  type="primary" 
                  @click="applyPromoCode"
                  :loading="processingAction"
                >
                  应用
                </el-button>
              </div>
            </div>
            
            <div v-if="discount > 0" class="summary-row discount-row">
              <span>折扣:</span>
              <span class="discount-amount">-¥{{ formatPrice(discount) }}</span>
            </div>
            
            <div class="summary-row total-row">
              <span>总计:</span>
              <span class="total-amount">¥{{ formatPrice(total) }}</span>
            </div>
          </div>
          
          <div class="checkout-buttons">
            <el-button 
              type="primary" 
              size="large" 
              @click="showPaymentDialog" 
              class="checkout-btn"
              :loading="processingAction"
            >
              结账
            </el-button>
            
            <p class="checkout-note">
              请注意：订单一旦提交，将无法编辑或取消。
            </p>
          </div>
        </el-card>
        
        <!-- 购物车商品列表 -->
        <el-card class="cart-items-card">
          <template #header>
            <div class="card-header">
              <span>购物车商品</span>
              <el-button 
                type="danger" 
                text 
                @click="clearCart" 
                v-if="cartItems.length > 0"
                :loading="processingAction"
              >
                清空购物车
              </el-button>
            </div>
          </template>
          
          <div class="cart-items">
            <div class="cart-header">
              <div class="select-col">
                <el-checkbox 
                  v-model="selectAll"
                  @change="handleSelectAllChange"
                />
              </div>
              <div class="product-col">商品信息</div>
              <div class="price-col">单价</div>
              <div class="quantity-col">数量</div>
              <div class="total-col">小计</div>
              <div class="action-col">操作</div>
            </div>
            
            <div v-for="item in cartItems" :key="item.id" class="cart-item">
              <div class="select-col">
                <el-checkbox 
                  v-model="item.selected"
                  @change="handleItemSelectChange"
                />
              </div>
              <div class="item-col">
                <div class="product-info">
                  <router-link :to="`/product/${item.product_id}`">
                    <el-image 
                      :src="formatImageUrl(item.image)" 
                      :alt="item.name"
                      class="product-image"
                    />
                  </router-link>
                  <div class="product-details">
                    <router-link :to="`/product/${item.product_id}`" class="product-name">
                      {{ item.name }}
                    </router-link>
                    <div class="product-attrs" v-if="item.attributes">
                      <el-tag 
                        v-for="(value, key) in item.attributes" 
                        :key="key"
                        size="small"
                        effect="plain"
                        class="attr-tag"
                      >
                        {{ key }}: {{ value }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="price-col">
                <el-tag type="danger">¥{{ formatPrice(item.price) }}</el-tag>
              </div>
              
              <div class="quantity-col">
                <el-input-number 
                  v-model="item.quantity" 
                  :min="1" 
                  :max="item.stock || 99"
                  size="small"
                  @change="(val) => updateQuantity(item, val)"
                  :disabled="processingAction"
                />
              </div>
              
              <div class="total-col">
                <span class="item-total">¥{{ formatPrice(item.price * item.quantity) }}</span>
              </div>
              
              <div class="action-col">
                <el-button 
                  type="danger" 
                  size="small"
                  @click="removeItem(item)"
                  :loading="processingAction"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 礼品选项 -->
        <el-card class="gifting-options">
          <template #header>
            <div class="card-header">
              <span>礼品选项</span>
            </div>
          </template>
          
          <el-form>
            <el-form-item>
              <el-checkbox v-model="addGiftMessage">添加礼品留言</el-checkbox>
            </el-form-item>
            
            <el-form-item v-if="addGiftMessage">
              <el-input
                v-model="giftMessage"
                type="textarea"
                :rows="3"
                placeholder="请输入礼品留言，将随商品一起发送"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>

    <!-- 添加支付方式选择弹窗 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="选择支付方式"
      width="400px"
    >
      <div class="payment-methods">
        <el-radio-group v-model="selectedPaymentMethod">
          <div class="payment-method-option">
            <el-radio label="wechat">
              <div class="payment-method-content">
                <el-icon><ChatDotRound /></el-icon>
                <span>微信支付</span>
              </div>
            </el-radio>
          </div>
          
          <div class="payment-method-option">
            <el-radio label="alipay">
              <div class="payment-method-content">
                <el-icon><Money /></el-icon>
                <span>支付宝</span>
              </div>
            </el-radio>
          </div>
        </el-radio-group>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="processPayment" :loading="processingAction">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 支付二维码弹窗 -->
    <el-dialog
      v-model="qrcodeDialogVisible"
      title="请扫码支付"
      width="350px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="qrcode-container">
        <img v-if="paymentQrcode" :src="paymentQrcode" alt="支付二维码" class="payment-qrcode" />
        <el-skeleton v-else :rows="10" animated />
        
        <div class="payment-info">
          <div class="payment-amount">¥{{ formatPrice(total) }}</div>
          <div class="payment-order-id">订单号: {{ orderId }}</div>
          <div class="payment-method">
            <el-tag type="success" v-if="selectedPaymentMethod === 'wechat'">微信支付</el-tag>
            <el-tag type="primary" v-else-if="selectedPaymentMethod === 'alipay'">支付宝</el-tag>
          </div>
        </div>
      </div>
      
      <div class="payment-timer">
        <el-progress :percentage="paymentTimePercentage" :format="formatPaymentTime" />
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelPayment">取消支付</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 地址管理弹窗 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="editingAddress.id ? '编辑地址' : '添加地址'"
      width="500px"
    >
      <el-form :model="editingAddress" :rules="addressRules" ref="addressForm" label-width="80px">
        <el-form-item label="收件人" prop="recipient">
          <el-input v-model="editingAddress.recipient" placeholder="请输入收件人姓名" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editingAddress.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="省份" prop="province">
          <el-select v-model="editingAddress.province" placeholder="选择省份" style="width: 100%">
            <el-option 
              v-for="province in provinces" 
              :key="province.value" 
              :label="province.label" 
              :value="province.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="城市" prop="city">
          <el-select 
            v-model="editingAddress.city" 
            placeholder="选择城市"
            :disabled="!editingAddress.province"
            style="width: 100%"
          >
            <el-option 
              v-for="city in addressCities" 
              :key="city.value" 
              :label="city.label" 
              :value="city.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="editingAddress.address" placeholder="街道、门牌号等" />
        </el-form-item>
        
        <el-form-item label="邮编" prop="postcode">
          <el-input v-model="editingAddress.postcode" placeholder="邮政编码" />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="editingAddress.is_default">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress" :loading="processingAction">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, inject, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import HeaderNav from '../components/HeaderNav.vue'
import axios from '../utils/axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ChatDotRound, Money } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const cartItems = ref([])
const addGiftMessage = ref(false)
const giftMessage = ref('')
const promoCode = ref('')
const discount = ref(0)
const shipping = ref(0)
const showShippingOptions = ref(false)
const confirmDialogVisible = ref(false)
const itemToRemove = ref(null)
const processingAction = ref(false)
const baseURL = import.meta.env.VITE_API_URL || 'http://localhost:5000'

// 省份数据
const provinces = [
  { value: '北京市', label: '北京市' },
  { value: '上海市', label: '上海市' },
  { value: '广东省', label: '广东省' },
  { value: '江苏省', label: '江苏省' },
  { value: '浙江省', label: '浙江省' },
  { value: '四川省', label: '四川省' },
  { value: '湖北省', label: '湖北省' },
  { value: '湖南省', label: '湖南省' },
  { value: '河北省', label: '河北省' },
  { value: '河南省', label: '河南省' },
  // 可以添加更多省份
]

// 城市数据 - 根据选择的省份动态加载
const cities = computed(() => {
  const provinceCities = {
    '北京市': [{ value: '北京市', label: '北京市' }],
    '上海市': [{ value: '上海市', label: '上海市' }],
    '广东省': [
      { value: '广州市', label: '广州市' },
      { value: '深圳市', label: '深圳市' },
      { value: '珠海市', label: '珠海市' },
      { value: '佛山市', label: '佛山市' }
    ],
    '江苏省': [
      { value: '南京市', label: '南京市' },
      { value: '苏州市', label: '苏州市' },
      { value: '无锡市', label: '无锡市' },
      { value: '常州市', label: '常州市' }
    ],
    '浙江省': [
      { value: '杭州市', label: '杭州市' },
      { value: '宁波市', label: '宁波市' },
      { value: '温州市', label: '温州市' },
      { value: '嘉兴市', label: '嘉兴市' }
    ],
    '四川省': [
      { value: '成都市', label: '成都市' },
      { value: '绵阳市', label: '绵阳市' },
      { value: '德阳市', label: '德阳市' },
      { value: '自贡市', label: '自贡市' }
    ],
    // 可以添加更多省份的城市
  }
  
  return provinceCities[shippingAddress.value.province] || []
})

const shippingAddress = ref({
  country: 'CN',
  province: '',
  city: '',
  postcode: ''
})

// 价格计算
const subtotalAmount = ref(0)
const total = ref(0)
const totalItems = ref(0)

// 获取购物车数据
const fetchCart = async () => {
  try {
    loading.value = true;
    console.log('Fetching cart data...');
    const { data } = await axios.get('/api/cart');
    console.log('Cart response:', data);
    
    if (data.success && Array.isArray(data.items)) {
      cartItems.value = data.items;
      calculateTotal();
      console.log('Cart items loaded:', cartItems.value.length);
    } else if (Array.isArray(data)) {
      // 兼容旧格式
      cartItems.value = data;
      calculateTotal();
      console.log('Cart items loaded (legacy format):', cartItems.value.length);
    } else {
      console.error('Unexpected cart data format:', data);
      ElMessage.error(data.message || '获取购物车失败');
      cartItems.value = [];
      calculateTotal(); // 确保即使购物车为空也计算总价
    }
  } catch (error) {
    console.error('Error fetching cart:', error);
    ElMessage.error('获取购物车失败');
    cartItems.value = [];
    calculateTotal(); // 确保即使出错也计算总价
  } finally {
    loading.value = false;
  }
};

// 更新商品数量
const updateQuantity = async (item, newQuantity) => {
  try {
    processingAction.value = true;
    
    // 防止数量小于1
    if (newQuantity < 1) {
      item.quantity = 1;
      calculateTotal();
      return;
    }
    
    // 保存原始数量，以便在失败时恢复
    const originalQuantity = item.quantity;
    
    // 先更新本地数量，提供即时反馈
    item.quantity = newQuantity;
    calculateTotal();
    
    const { data } = await axios.put(`/api/cart/${item.id}`, {
      quantity: newQuantity
    });
    
    if (data.success) {
      item.quantity = data.data.quantity;
      calculateTotal();
      ElMessage({
        type: 'success',
        message: '更新成功',
        center: true,
        showClose: false,
        duration: 2000
      });
    } else {
      // 恢复原始数量
      item.quantity = originalQuantity;
      calculateTotal();
      ElMessage.error(data.message || '更新数量失败');
    }
  } catch (error) {
    console.error('Error updating quantity:', error);
    // 恢复原始数量
    item.quantity = originalQuantity;
    calculateTotal();
    ElMessage.error('更新数量失败，请稍后再试');
  } finally {
    processingAction.value = false;
  }
};

// 删除商品
const removeItem = async (item) => {
  try {
    processingAction.value = true;
    const { data } = await axios.delete(`/api/cart/${item.id}`);
    
    if (data.success) {
      cartItems.value = cartItems.value.filter(i => i.id !== item.id);
      calculateTotal();
      
      ElMessage({
        type: 'success',
        message: '删除成功',
        center: true,
        showClose: false,
        duration: 2000
      });
      
      // 更新导航栏购物车数量
      const headerNavMethods = inject('headerNavMethods', null);
      if (headerNavMethods) {
        headerNavMethods.refreshCart();
      }
    } else {
      ElMessage.error(data.message || '移除商品失败');
      fetchCart();
    }
  } catch (error) {
    console.error('Error removing item:', error);
    ElMessage.error('移除商品失败，请稍后再试');
    fetchCart();
  } finally {
    processingAction.value = false;
  }
};

// 清空购物车
const clearCart = async () => {
  try {
    ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      processingAction.value = true;
      
      // 调用清空购物车API
      const { data } = await axios.delete('/api/cart');
      
      if (data.success) {
        cartItems.value = [];
        calculateTotal();
        ElMessage.success('购物车已清空');
        
        // 更新导航栏购物车数量
        const headerNavMethods = inject('headerNavMethods', null);
        if (headerNavMethods) {
          headerNavMethods.refreshCart();
        }
      } else {
        ElMessage.error(data.message || '清空购物车失败');
      }
      
      processingAction.value = false;
    }).catch(() => {});
  } catch (error) {
    console.error('Error clearing cart:', error);
    ElMessage.error('清空购物车失败');
    processingAction.value = false;
  }
}

// 应用优惠码
const applyPromoCode = async () => {
  if (!promoCode.value.trim()) {
    ElMessage.warning('请输入优惠码');
    return;
  }
  
  try {
    processingAction.value = true;
    const { data } = await axios.post('/api/cart/promo', { 
      code: promoCode.value.trim()
    });
    
    if (data.success && data.discount) {
      discount.value = data.discount.discountAmount;
      calculateTotal(); // 重新计算总价
      ElMessage.success(`优惠码已应用，优惠金额：¥${formatPrice(data.discount.discountAmount)}`);
    } else {
      ElMessage.warning(data.message || '优惠码无效');
    }
  } catch (error) {
    console.error('Error applying promo code:', error);
    ElMessage.error(error.response?.data?.message || '应用优惠码失败');
  } finally {
    processingAction.value = false;
  }
};

// 计算配送费
const calculateShipping = async () => {
  const { country, province, city, postcode } = shippingAddress.value
  
  if (!country || !province || !city || !postcode) {
    ElMessage.warning('请填写完整的配送地址信息')
    return
  }
  
  if (processingAction.value) return
  
  try {
    processingAction.value = true
    const { data } = await axios.post('/api/cart/shipping', shippingAddress.value)
    
    shipping.value = data.shipping_cost || 0
    ElMessage.success(`配送费已更新: ¥${formatPrice(shipping.value)}`)
    showShippingOptions.value = false
  } catch (error) {
    console.error('Error calculating shipping:', error)
    ElMessage.error('计算配送费失败')
  } finally {
    processingAction.value = false
  }
}

// 结账
const checkout = async () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法结账')
    return
  }
  
  if (processingAction.value) return
  
  try {
    processingAction.value = true
    
    // 保存礼品信息
    if (addGiftMessage.value) {
      localStorage.setItem('giftMessage', giftMessage.value)
    } else {
      localStorage.removeItem('giftMessage')
    }
    
    // 跳转到结账页面
    router.push('/checkout')
  } catch (error) {
    console.error('Error during checkout:', error)
    ElMessage.error('结账过程中出错')
  } finally {
    processingAction.value = false
  }
}

// 格式化图片URL
const formatImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `/uploads/${url}`
}

// 格式化价格
const formatPrice = (price) => {
  return parseFloat(price).toFixed(2);
};

// 监听省份变化，重置城市
watch(() => shippingAddress.value.province, (newProvince) => {
  shippingAddress.value.city = ''
})

onMounted(async () => {
  // 检查URL参数中的支付状态
  const paymentStatus = route.query.payment_status;
  const orderNo = route.query.order_no;
  
  if (paymentStatus === 'success' && orderNo) {
    try {
      ElMessage.success('支付处理中，请稍候...');
      
      // 查询订单信息
      const { data: orderData } = await axios.get(`/api/orders/by-number/${orderNo}`);
      
      if (orderData.success && orderData.order) {
        const orderId = orderData.order.id;
        
        // 查询支付状态
        const { data: paymentData } = await axios.get(`/api/payments/status/${orderId}`);
        
        if (paymentData.success) {
          // 清除购物车中已购买的商品
          await axios.post('/api/cart/clear-paid', { order_no: orderNo });
          
          ElMessage.success('支付成功！');
          
          // 更新导航栏购物车数量
          const headerNavMethods = inject('headerNavMethods', null);
          if (headerNavMethods) {
            headerNavMethods.refreshCart();
          }
          
          // 清除URL参数
          router.replace({
            path: '/cart',
            query: {}
          });
        } else {
          ElMessage.error('支付状态查询失败，请联系客服');
        }
      } else {
        ElMessage.error('订单信息获取失败，请联系客服');
      }
    } catch (error) {
      console.error('Error handling payment success:', error);
      ElMessage.error('处理支付结果时出错，请联系客服');
    }
  }
  
  // 获取购物车数据
  await fetchCart();
  fetchAddresses();
});

// 添加新的响应式变量
const addresses = ref([])
const selectedAddressId = ref(null)
const selectedAddress = ref(null)
const addressDialogVisible = ref(false)
const editingAddress = ref({
  recipient: '',
  phone: '',
  province: '',
  city: '',
  address: '',
  postcode: '',
  is_default: false
})
const paymentDialogVisible = ref(false)
const selectedPaymentMethod = ref('')
const qrcodeDialogVisible = ref(false)
const paymentQrcode = ref('')
const orderId = ref('')
const paymentTimePercentage = ref(100)
const paymentTimer = ref(null)
const paymentTimeout = ref(300) // 5分钟支付时间
const addressForm = ref(null)
const addressCities = computed(() => {
  const provinceCities = {
    '北京市': [{ value: '北京市', label: '北京市' }],
    '上海市': [{ value: '上海市', label: '上海市' }],
    '广东省': [
      { value: '广州市', label: '广州市' },
      { value: '深圳市', label: '深圳市' },
      { value: '珠海市', label: '珠海市' },
      { value: '佛山市', label: '佛山市' }
    ],
    '江苏省': [
      { value: '南京市', label: '南京市' },
      { value: '苏州市', label: '苏州市' },
      { value: '无锡市', label: '无锡市' },
      { value: '常州市', label: '常州市' }
    ],
    '浙江省': [
      { value: '杭州市', label: '杭州市' },
      { value: '宁波市', label: '宁波市' },
      { value: '温州市', label: '温州市' },
      { value: '嘉兴市', label: '嘉兴市' }
    ],
    // 可以添加更多省份的城市
  }
  
  return provinceCities[editingAddress.value.province] || []
})

// 地址表单验证规则
const addressRules = {
  recipient: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请选择省份', trigger: 'change' }
  ],
  city: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  postcode: [
    { pattern: /^\d{6}$/, message: '请输入正确的邮政编码', trigger: 'blur' }
  ]
}

// 监听编辑地址的省份变化，重置城市
watch(() => editingAddress.value.province, () => {
  editingAddress.value.city = ''
})

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const { data } = await axios.get('/api/cart/addresses');
    addresses.value = Array.isArray(data) ? data : [];
  } catch (error) {
    console.error('Error fetching addresses:', error);
    ElMessage.error('获取地址列表失败');
  }
};

// 处理地址选择变化
const handleAddressChange = (addressId) => {
  const selected = addresses.value.find(addr => addr.id === addressId);
  if (selected) {
    selectedAddress.value = selected;
    
    // 如果已经计算过配送费，使用新地址重新计算
    if (shipping.value > 0) {
      calculateShipping();
    }
  }
};

// 格式化地址标签
const formatAddressLabel = (address) => {
  return `${address.name} ${address.phone}`;
};

// 格式化完整地址
const formatAddress = (address) => {
  return `${address.province} ${address.city} ${address.address}`;
};

// 显示地址管理弹窗
const showAddressDialog = (address = null) => {
  if (address) {
    // 编辑现有地址
    editingAddress.value = {
      id: address.id,
      recipient: address.name,
      phone: address.phone,
      province: address.province,
      city: address.city,
      address: address.address,
      postcode: address.postcode,
      is_default: address.is_default === 1
    };
  } else {
    // 添加新地址
    editingAddress.value = {
      recipient: '',
      phone: '',
      province: '',
      city: '',
      address: '',
      postcode: '',
      is_default: false
    };
  }
  
  addressDialogVisible.value = true;
};

// 保存地址
const saveAddress = async () => {
  try {
    if (!addressForm.value) return;
    
    await addressForm.value.validate(async (valid) => {
      if (valid) {
        processingAction.value = true;
        
        try {
          // 确保使用正确的字段名称
          const addressData = {
            name: editingAddress.value.recipient,
            phone: editingAddress.value.phone,
            province: editingAddress.value.province,
            city: editingAddress.value.city,
            address: editingAddress.value.address,
            postcode: editingAddress.value.postcode,
            is_default: editingAddress.value.is_default ? 1 : 0
          };
          
          console.log('Saving address data:', addressData);
          
          const method = editingAddress.value.id ? 'put' : 'post';
          const url = editingAddress.value.id 
            ? `/api/addresses/${editingAddress.value.id}` 
            : '/api/addresses';
          
          const response = await axios[method](url, addressData);
          console.log('Address save response:', response);
          
          if (response.data) {
            ElMessage.success(editingAddress.value.id ? '地址已更新' : '地址已添加');
            addressDialogVisible.value = false;
            
            // 刷新地址列表
            await fetchAddresses();
          } else {
            const errorMsg = response.data && response.data.message 
              ? response.data.message 
              : '保存地址失败';
            ElMessage.error(errorMsg);
          }
        } catch (error) {
          console.error('Error saving address:', error);
          
          // 更详细的错误信息
          let errorMsg = '保存地址失败';
          if (error.response && error.response.data) {
            console.error('Error response data:', error.response.data);
            errorMsg = error.response.data.message || errorMsg;
          }
          
          ElMessage.error(errorMsg);
        } finally {
          processingAction.value = false;
        }
      }
    });
  } catch (error) {
    console.error('Error validating form:', error);
    processingAction.value = false;
  }
};

// 显示支付方式选择弹窗
const showPaymentDialog = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }
  
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  
  paymentDialogVisible.value = true
  selectedPaymentMethod.value = ''
}

// 处理支付
const processPayment = async () => {
  if (!selectedPaymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }
  
  if (processingAction.value) return
  
  try {
    processingAction.value = true
    
    // 创建订单
    const orderData = {
      items: cartItems.value.map(item => ({
        product_id: item.product_id || item.id,
        quantity: item.quantity,
        attributes: item.attributes
      })),
      shipping_address_id: selectedAddress.value.id,
      payment_method: selectedPaymentMethod.value,
      gift_message: addGiftMessage.value ? giftMessage.value : null,
      promo_code: promoCode.value || null,
      discount: discount.value,
      shipping_fee: shipping.value
    }
    
    console.log('Creating order with data:', orderData);
    
    const { data } = await axios.post('/api/orders', orderData)
    
    if (data.success) {
      // 关闭支付方式选择弹窗
      paymentDialogVisible.value = false
      
      // 保存订单ID
      orderId.value = data.order.order_number
      
      // 获取支付信息
      const paymentResponse = await axios.post('/api/payments/create', {
        order_id: data.order.id,
        payment_method: selectedPaymentMethod.value,
        amount: total.value
      })
      
      console.log('Payment response:', paymentResponse);
      
      if (paymentResponse.data.success) {
        if (selectedPaymentMethod.value === 'alipay') {
          // 支付宝支付
          if (paymentResponse.data.is_form) {
            // 如果返回的是HTML表单，创建一个临时div来提交表单
            const div = document.createElement('div');
            div.innerHTML = paymentResponse.data.payment_html;
            document.body.appendChild(div);
            
            // 表单会自动提交，因为HTML中包含了自动提交的脚本
          } else {
            // 如果返回的是URL，直接跳转
            window.location.href = paymentResponse.data.payment_url;
          }
        } else if (selectedPaymentMethod.value === 'wechat') {
          // 微信支付 - 显示提示
          ElMessage.warning('微信支付功能暂未开发')
          processingAction.value = false
        }
      } else {
        ElMessage.error(paymentResponse.data.message || '创建支付失败')
        processingAction.value = false
      }
    } else {
      ElMessage.error(data.message || '创建订单失败')
      processingAction.value = false
    }
  } catch (error) {
    console.error('Error processing payment:', error)
    let errorMessage = '处理支付失败'
    
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    }
    
    ElMessage.error(errorMessage)
    processingAction.value = false
  }
}

// 开始支付倒计时
const startPaymentTimer = () => {
  // 清除之前的计时器
  if (paymentTimer.value) {
    clearInterval(paymentTimer.value)
  }
  
  let remainingTime = paymentTimeout.value
  paymentTimePercentage.value = 100
  
  paymentTimer.value = setInterval(() => {
    remainingTime--
    paymentTimePercentage.value = (remainingTime / paymentTimeout.value) * 100
    
    if (remainingTime <= 0) {
      clearInterval(paymentTimer.value)
      qrcodeDialogVisible.value = false
      ElMessage.warning('支付超时，请稍后再试')
    }
  }, 1000)
}

// 格式化支付倒计时
const formatPaymentTime = (percentage) => {
  const remainingSeconds = Math.floor((percentage / 100) * paymentTimeout.value)
  const minutes = Math.floor(remainingSeconds / 60)
  const seconds = remainingSeconds % 60
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
}

// 取消支付
const cancelPayment = () => {
  ElMessageBox.confirm(
    '确定要取消支付吗？',
    '取消支付',
    {
      confirmButtonText: '确定',
      cancelButtonText: '返回支付',
      type: 'warning'
    }
  ).then(() => {
    if (paymentTimer.value) {
      clearInterval(paymentTimer.value)
    }
    qrcodeDialogVisible.value = false
  }).catch(() => {})
}

// 轮询支付状态
const pollPaymentStatus = async (orderId) => {
  const checkStatus = async () => {
    try {
      const { data } = await axios.get(`/api/payments/status/${orderId}`)
      
      if (data.success && data.status === 'paid') {
        // 支付成功
        if (paymentTimer.value) {
          clearInterval(paymentTimer.value)
        }
        qrcodeDialogVisible.value = false
        ElMessage.success('支付成功！')
        
        // 清空购物车
        cartItems.value = []
        
        // 更新导航栏购物车数量
        const headerNavMethods = inject('headerNavMethods', null)
        if (headerNavMethods) {
          headerNavMethods.refreshCart()
        }
        
        // 更新订单状态为已支付
        try {
          await axios.put(`/api/orders/${orderId}/status`, {
            status: 'paid'
          });
          console.log('订单状态已更新为已支付');
        } catch (updateError) {
          console.error('更新订单状态失败:', updateError);
        }
        
        // 跳转到订单详情页
        router.push(`/order/${orderId}`)
        return true
      }
      
      return false
    } catch (error) {
      console.error('Error checking payment status:', error)
      return false
    }
  }
  
  // 每3秒检查一次，最多检查100次（5分钟）
  let attempts = 0
  const maxAttempts = 100
  
  const interval = setInterval(async () => {
    attempts++
    
    const success = await checkStatus()
    
    if (success || attempts >= maxAttempts || !qrcodeDialogVisible.value) {
      clearInterval(interval)
    }
  }, 3000)
}

// 计算购物车总价
const calculateTotal = () => {
  // 只计算选中商品的总价
  subtotalAmount.value = cartItems.value.reduce((sum, item) => {
    return sum + (item.selected ? item.price * item.quantity : 0);
  }, 0);
  
  // 确保折扣不超过小计
  if (discount.value > 0) {
    discount.value = Math.min(discount.value, subtotalAmount.value);
  }
  
  // 计算总价 = 小计 + 运费 - 折扣
  total.value = Math.max(0, subtotalAmount.value + shipping.value - discount.value);
  
  // 更新选中商品总数
  totalItems.value = cartItems.value.reduce((sum, item) => 
    sum + (item.selected ? item.quantity : 0), 0);
}

// 添加商品选择功能
const selectAll = ref(false)

// 处理全选
const handleSelectAllChange = (val) => {
  cartItems.value.forEach(item => {
    item.selected = val
  })
  calculateTotal()
}

// 处理单个商品选择
const handleItemSelectChange = () => {
  selectAll.value = cartItems.value.every(item => item.selected)
  calculateTotal()
}
</script>

<style scoped>
.cart-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.breadcrumb {
  padding: 15px 20px;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header-card {
  margin-bottom: 20px;
}

.cart-title {
  margin: 0;
  font-size: 24px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  grid-template-rows: auto auto;
  gap: 20px;
}

.cart-items-card {
  grid-column: 1;
  grid-row: 1 / span 2;
}

.order-summary {
  grid-column: 2;
  grid-row: 1;
}

.gifting-options {
  grid-column: 2;
  grid-row: 2;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.cart-header {
  display: grid;
  grid-template-columns: 60px 3fr 1fr 1fr 1fr 1fr;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
  background-color: #f8f9fa;
}

.cart-item {
  display: grid;
  grid-template-columns: 60px 3fr 1fr 1fr 1fr 1fr;
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
  align-items: center;
}

.select-col {
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.product-col {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-details {
  flex: 1;
}

.product-name {
  color: #333;
  font-weight: 500;
  text-decoration: none;
  margin-bottom: 5px;
  display: block;
}

.product-name:hover {
  color: var(--el-color-primary);
}

.attr-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.item-total {
  font-weight: bold;
  color: #ff6b6b;
}

.summary-content {
  margin-bottom: 20px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.shipping-row,
.promo-row {
  align-items: flex-start;
}

.shipping-info,
.promo-input {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 5px;
}

.shipping-options {
  background: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin: 10px 0 15px;
}

.discount-amount {
  color: #ff6b6b;
  font-weight: bold;
}

.total-row {
  font-size: 18px;
  font-weight: bold;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.total-amount {
  color: #ff6b6b;
}

.checkout-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.checkout-btn {
  width: 100%;
}

.checkout-note {
  font-size: 12px;
  color: #666;
  margin-top: 15px;
  text-align: center;
}

.empty-cart {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 60px 20px;
  text-align: center;
}

.loading {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

@media (max-width: 992px) {
  .cart-container {
    grid-template-columns: 1fr;
    grid-template-rows: auto auto auto;
  }
  
  .cart-items-card,
  .order-summary,
  .gifting-options {
    grid-column: 1;
  }
  
  .cart-items-card {
    grid-row: 1;
  }
  
  .order-summary {
    grid-row: 2;
  }
  
  .gifting-options {
    grid-row: 3;
  }
}

@media (max-width: 768px) {
  .cart-header {
    display: none;
  }
  
  .cart-item {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .price-col,
  .quantity-col,
  .total-col,
  .action-col {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .price-col::before {
    content: '单价:';
    font-weight: 500;
  }
  
  .quantity-col::before {
    content: '数量:';
    font-weight: 500;
  }
  
  .total-col::before {
    content: '小计:';
    font-weight: 500;
  }
  
  .action-col {
    justify-content: flex-end;
  }
}

/* 地址选择器和显示样式优化 */
.address-selector {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
}

.address-option {
  padding: 8px 0;
}

.address-option-name {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 6px;
}

.address-option-name .name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.address-option-name .phone {
  color: #606266;
}

.address-option-detail {
  color: #909399;
  font-size: 13px;
  line-height: 1.4;
}

.selected-address-detail {
  margin-top: 12px;
  padding: 16px;
  background-color: var(--el-color-success-light-9);
  border: 1px solid var(--el-color-success-light-7);
  border-radius: 4px;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 10px;
}

.address-header .name {
  font-size: 15px;
  font-weight: 500;
  color: var(--el-color-success-dark-2);
}

.address-header .phone {
  color: var(--el-color-success-dark-2);
}

.address-content {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  color: var(--el-color-success-dark-2);
  line-height: 1.5;
}

.address-content i {
  color: var(--el-color-success);
  font-size: 16px;
  margin-top: 2px;
}

.address-postcode {
  margin-top: 8px;
  color: var(--el-color-info);
  font-size: 13px;
}

.address-row {
  margin-bottom: 16px;
}

:deep(.el-button--link) {
  margin-top: 8px;
  padding: 0;
  height: auto;
  font-size: 13px;
}
</style> 